    #include "connector.h"
#include <QDebug>
#include <QHostAddress>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkProxy>
#include <QSettings>

Connector::Connector(QObject *parent) :
    QObject(parent)
{
    http=new QNetworkAccessManager();
    connect(http, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(requestFinnished(QNetworkReply*)));
}
void Connector::connectEd(QString ip){
    socket=new QTcpSocket();
    socket->connectToHost(ip,2200);
    connect(socket, SIGNAL(readyRead()), this, SLOT(parseMessage()));
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(displayError(QAbstractSocket::SocketError)));

};

void Connector::send(int hash, QString answer){

    QDomDocument doc("CaptchaSolver");
    QDomElement root = doc.createElement("captcha");
    doc.appendChild(root);

    QDomElement Acttag = doc.createElement("action");
    root.appendChild(Acttag);
    Acttag.setAttribute("action","answer");

    QDomElement Hashtag = doc.createElement("hash");
    root.appendChild(Hashtag);

    QDomText Hasht = doc.createTextNode(QString().setNum(hash));
    Hashtag.appendChild(Hasht);

    QDomElement Adrtag = doc.createElement("caption");
    root.appendChild(Adrtag);

    QDomText Adrt = doc.createTextNode(answer);
    Adrtag.appendChild(Adrt);


    QString xml = doc.toString();

    socket->write(xml.toAscii());
    socket->flush();

}

void Connector::requestFinnished(QNetworkReply* reply){
    qDebug()<<"decodeReady";
    int hash=hashMap.take(reply->url().toString());
    emit decode(hash, reply);

}

QString Connector::getSingleTagValue(QDomNode node, QString name){
    QDomNode tag=node.namedItem(name);
    if(tag.isNull()){
        qDebug()<<"Could not find tag "<<name;
    };
    QDomElement el=tag.toElement();
    if(el.isNull()){
        qDebug()<<name<<" is not element";
    }
    return el.text();

};

QString Connector::getSingleAttributeValue(QDomNode node, QString name){
    QDomNode act=node.namedItem(name);
    if(!act.hasAttributes()){
        qDebug()<<"No attributes with "<<name;
        return "";
    }
    if(act.attributes().length()!=1){
        qDebug()<<"Invalid number of "<<name<<" attributes: "<<act.attributes().length();
        return "";
    }

    return QString(act.attributes().item(0).toAttr().value());

};

void Connector::parseMessage(){
    QDomDocument doc;
    QString part(socket->readAll());
    message+=part;
    if(!doc.setContent(message)){
        qDebug()<<"Not complete message";
        return;
    };
    message="";

    QDomNodeList list=doc.elementsByTagName("captcha");
    if(list.isEmpty()){
        qDebug()<<"Nie znaleziono tagu captcha";
        return;
    }

    for(unsigned int i=0; i<list.length(); i++){
            qDebug()<<"Question";
            QString address(getSingleTagValue(list.at(i), "address"));
            QString hash(getSingleTagValue(list.at(i), "hash"));
            if(hash=="" || address==""){
                qDebug()<<"problem decoding message "<<list.at(i).toDocument().toString() ;
            }else{
                qDebug()<<hash;
                qDebug()<<address;
                downloadPage(hash.toInt(), address);
            }
    }
};

void Connector::downloadPage(int hash, QString url){
    QNetworkReply *rply = http->get(QNetworkRequest(QUrl(url)));
    connect(rply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(displayError(QNetworkReply::NetworkError)));
    hashMap.insert(url, hash);
}

void Connector::proxySwitched(bool use,QString addr,int port){
    if(use){
        socket->setProxy(QNetworkProxy(QNetworkProxy::Socks5Proxy, addr, port));
    }else{
        socket->setProxy(QNetworkProxy::NoProxy);
    }
};

void Connector::displayError(QNetworkReply::NetworkError err){
    qDebug()<<err;

    //delete socket;
    //emit connErr(err);
};

void Connector::displayError(QAbstractSocket::SocketError err){
    //qDebug()<<err;
    socket->close();
    //delete socket;
    emit connErr(err);
};
